#
# Copyright 2020, Data61, CSIRO (ABN 41 687 119 230)
#
# SPDX-License-Identifier: BSD-2-Clause
#

# This module provides a function GenerateSimulateScript which will place a `simulate`
# script in the build directory for running produced images in Qemu.
include_guard(GLOBAL)

require_file(SIMULATE_SCRIPT simulate.py PATHS "${CMAKE_CURRENT_LIST_DIR}/simulate_scripts/")
require_file(GDB_SCRIPT launch_gdb.py PATHS "${CMAKE_CURRENT_LIST_DIR}/simulate_scripts/")
require_file(CONFIGURE_FILE_SCRIPT configure_file.cmake PATHS "${CMAKE_CURRENT_LIST_DIR}/simulate_scripts/")

# Helper function that generates targets that will attempt to generate a ./simulate style script
function(GenerateSimulateScript)
  get_property(CORE_TARGET_IMAGE_PATH_PROPERTY GLOBAL PROPERTY CORE_TARGET_IMAGE_PATH)
  get_property(CORE_TARGET_NAME_PROPERTY GLOBAL PROPERTY CORE_TARGET_NAME)
  if(NOT CORE_TARGET_IMAGE_PATH_PROPERTY)
    return()
  endif()

  if(${ARCH} STREQUAL "arm64")
    set(qemu_binary_machine "qemu-system-aarch64")
    set(qemu_sim_cpu "cortex-a57")
    set(qemu_sim_machine "type=virt,gic-version=3")
    set(qemu_sim_device "-device virtio-scsi-device")
    set(qemu_sim_extra "${qemu_sim_device} -smp 8 -m 4G")

    set(gdb_binary "gdb-multiarch")
  else()
    message(FATAL_ERROR "NOT SUPPORT ${ARCH} simulate")
  endif()

  set(sim_path "${CMAKE_BINARY_DIR}/simulate")
  set(gdb_path "${CMAKE_BINARY_DIR}/launch_gdb")

  add_custom_command(
    OUTPUT ${sim_path}
    COMMAND
      ${CMAKE_COMMAND} -DCONFIGURE_INPUT_FILE=${SIMULATE_SCRIPT}
        -DCONFIGURE_OUTPUT_FILE=${sim_path} -DQEMU_SIM_BINARY=${qemu_binary_machine}
        -DQEMU_SIM_CPU=${qemu_sim_cpu} -DQEMU_SIM_MACHINE=${qemu_sim_machine}
        -DQEMU_SIM_EXTRA=${qemu_sim_extra}
        -DQEMU_SIM_IMAGE_FILE=${CORE_TARGET_IMAGE_PATH_PROPERTY}
        -P ${CONFIGURE_FILE_SCRIPT}
    COMMAND chmod +x ${sim_path}
    VERBATIM COMMAND_EXPAND_LISTS
  )
  add_custom_target(simulate_gen DEPENDS ${sim_path})
  add_dependencies(${CORE_TARGET_NAME_PROPERTY} simulate_gen)

  add_custom_command(
    OUTPUT ${gdb_path}
    COMMAND
      ${CMAKE_COMMAND} -DCONFIGURE_INPUT_FILE=${GDB_SCRIPT}
        -DCONFIGURE_OUTPUT_FILE=${gdb_path} -DGDB_BINARY=${gdb_binary}
        -DQEMU_SIM_IMAGE_FILE=${CORE_TARGET_IMAGE_PATH_PROPERTY}
        -P ${CONFIGURE_FILE_SCRIPT}
    COMMAND chmod +x ${gdb_path}
    VERBATIM COMMAND_EXPAND_LISTS
  )
  add_custom_target(gdb_gen DEPENDS ${gdb_path})
  add_dependencies(${CORE_TARGET_NAME_PROPERTY} gdb_gen)
endfunction()
